<template>
  <el-card class="my-5">
    <h1 class="mb-4">{{ $t("基本信息") }}</h1>
    <el-form :model="form" ref="formRef" label-width="240px" :rules="rules">
      <el-form-item :label="$t('充值金额')" prop="amount">
        <el-input
          v-model="form.amount"
          type="number"
          :placeholder="$t('请输入充值金额')"
          style="width: 50%"
        ></el-input>
        <div v-if="available.warning" class="el-form-item__error">
          {{ available.warning }}
        </div>
      </el-form-item>
      <el-form-item :label="$t('充值币种')" prop="currency">
        <el-select
          :popper-append-to-body="false"
          popper-class="optionsContent"
          v-model="form.currency"
          :placeholder="$t('请选择币种')"
          @change="handleCurrencyChange"
          style="width: 50%"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.key"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('账户余额')" v-if="form.currency != ''">
        {{ available.available }}
      </el-form-item>
      <el-form-item :label="$t('收款账户')" prop="bank_card_id">
        <el-select
          v-model="form.bank_card_id"
          :placeholder="$t('请选择收款账户')"
          style="width: 50%"
        >
          <el-option
            v-for="(bankCard, index) in bankCards"
            :key="index"
            :label="bankCard.name || bankCard.card_name"
            :value="bankCard.card_id"
          >
            <!-- {{ bankCard.name }} - {{ bankCard.card_name }} -->
            {{ bankCard.name || bankCard.card_name }}
          </el-option>
        </el-select>
      </el-form-item>
      <p v-for="(bankT, index) in bankCards" :key="index">
        <el-card v-if="bankT.card_id == form.bank_card_id" class="bank-details">
          <el-row class="mb-1">
            <el-col :span="6">{{ $t("银行名称") }}</el-col>
            <el-col :span="18">{{ bankT.bank }}</el-col>
          </el-row>
          <el-row class="mb-1">
            <el-col :span="6">{{ $t("银行地址") }}</el-col>
            <el-col :span="18">{{ bankT.bank_address }}</el-col>
          </el-row>
          <el-row class="mb-1">
            <el-col :span="6">{{ $t("银行账号") }}</el-col>
            <el-col :span="18">{{ bankT.card_number }}</el-col>
          </el-row>
          <el-row class="mb-1">
            <el-col :span="6">{{ $t("收款人名称") }}</el-col>
            <el-col :span="18">{{ bankT.card_name }}</el-col>
          </el-row>
          <el-row class="mb-1">
            <el-col :span="6">{{ $t("SWIFT码") }}</el-col>
            <el-col :span="18">{{ bankT.swift_code }}</el-col>
          </el-row>
          <el-row class="mb-1" v-if="bankT.extended">
            <el-col :span="6">{{ $t("银行补充信息") }}</el-col>
            <el-col :span="18">{{ bankT.extended }}</el-col>
          </el-row>
        </el-card>
      </p>
      <h1 class="mb-4">{{ $t("支付信息") }}</h1>
      <el-form-item :label="$t('付款账户')">
        <!--<el-select v-model="form.pay_cards_list_ex" clearable :placeholder="$t('选择已录入账号')"-->
        <!--@change="handlePaymentCardChange" style="width: 50%">-->
        <el-select
          v-model="form.pay_cards_list_ex"
          filterable
          remote
          reserve-keyword
          remote-show-suffix
          :placeholder="$t('选择已录入账号')"
          :remote-method="remoteMethod"
          :loading="loading"
          @change="handlePaymentCardChange"
          style="width: 50%"
        >
          <el-option
            v-for="item in selectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('付款银行名称')" prop="pay_bank_name">
        <el-input
          v-model="form.pay_bank_name"
          :placeholder="$t('请输入付款银行名称')"
          style="width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('付款银行账号')" prop="pay_bank_card_number">
        <el-input
          v-model="form.pay_bank_card_number"
          :placeholder="$t('请输入付款银行账号')"
          style="width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('付款人名称')" prop="pay_card_name">
        <el-input
          v-model="form.pay_card_name"
          :placeholder="$t('请输入付款人名称')"
          style="width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('支付时间')" prop="pay_time">
        <el-date-picker
          v-model="form.pay_time"
          type="datetime"
          :placeholder="$t('请选择支付时间')"
          style="width: 50%"
        />
      </el-form-item>
      <el-form-item label="SWIFT/BIC">
        <el-input
          v-model="form.pay_card_swift"
          :placeholder="$t('请输入SWIFT/BIC码')"
          style="width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('付款银行地址')">
        <el-input
          v-model="form.pay_bank_address"
          :placeholder="$t('请输入付款银行地址')"
          style="width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('银行补充信息')">
        <el-input
          type="textarea"
          rows="2"
          v-model="form.pay_extended"
          :placeholder="$t('请输入银行补充信息（选填）')"
          style="width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('支付方式')">
        <el-input
          v-model="form.pay_way"
          :placeholder="$t('请输入支付方式（选填）')"
          style="width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('支付凭证流水号')">
        <el-input
          v-model="form.pay_order_no"
          :placeholder="$t('请输入支付凭证流水号（选填）')"
          style="width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('备注信息')">
        <el-input
          type="textarea"
          rows="2"
          v-model="form.description"
          :placeholder="$t('请输入备注信息（选填）')"
          style="width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('支付凭证（图片大小不超过1MB）')" prop="pay_img">
        <el-upload
          :file-list="fileList"
          :action="config.img_upload"
          :on-success="handleUploadSuccess"
          :headers="TOKENT_HEADER"
          list-type="picture-card"
        >
          <el-icon>
            <Plus />
          </el-icon>
          <template #file="{ file }">
            <div>
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <el-icon><zoom-in /></el-icon>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-dialog v-model="previewVisible">
        <img w-full :src="previewImageUrl" alt="Preview Image" />
      </el-dialog>
      <el-form-item>
        <el-button
          type="primary"
          :icon="SuccessFilled"
          size="large"
          class="w-48 mt-5"
          @click="showConfirmDialog"
          >{{ $t("确认提交") }}</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Plus, SuccessFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { config, TOKENT_HEADER } from "@/config/index";
import {
  rechargeSubmitApi,
  GetCurrencyApi,
  rechargeGetBankCardsApi,
  rechargePaymentCardsApi,
  getAssetBalanceApi,
} from "@/api/account/index";

import { timestamp } from "@/utils/utils";
import { useI18n } from "vue-i18n";
const router = useRouter();
const fileList = ref([]);
const formRef = ref();
const currencyList = ref([]);
const paymentCardsList = ref([]);
const available = ref({}); //可用余额
const previewImageUrl = ref("");
const previewVisible = ref(false);
const disabled = ref(false);
const { t } = useI18n();
// const getBankCardsList = ref([]);
const bankCards = ref([]);

const selectList = ref([]);
const selectOptions = ref([]);
const loading = ref(false);

const form = reactive({
  bank_card_id: "",
  amount: "",
  currency: "",
  pay_bank_name: "",
  pay_bank_address: "",
  pay_bank_card_number: "",
  pay_card_name: "",
  pay_card_swift: "",
  pay_time: "",
  pay_img: "",
});
// 分页
const pageable = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0,
});
// 参数
const param = (currency) => {
  return {
    page: pageable.pageNum,
    currency: currency,
    pagesize: pageable.pageSize,
  };
};

// 币种选择
const handleCurrency = async (value, amount) => {
  const res = await getAssetBalanceApi({
    currency: value,
    order_type: 0,
    amount: amount,
  });
  available.value = res;
};

const handleClick = () => {
  router.replace(`/account/recharge`);
};
// 校验
// t("login.userNameMessage")
const rules = {
  amount: [{ required: true, message: t("请输入充值金额"), trigger: "blur" }],
  currency: [{ required: true, message: t("请选择币种"), trigger: "change" }],
  bank_card_id: [
    { required: true, message: t("请选择收款账户"), trigger: "blur" },
  ],
  pay_bank_name: [
    { required: true, message: t("请输入银行名称"), trigger: "blur" },
  ],
  pay_bank_card_number: [
    { required: true, message: t("请输入银行账号"), trigger: "blur" },
  ],
  pay_card_name: [
    { required: true, message: t("请输入付款人名称"), trigger: "blur" },
  ],
  pay_time: [{ required: true, message: t("请选择付款时间"), trigger: "blur" }],
  pay_bank_address: [
    { required: true, message: t("请输入银行卡地址"), trigger: "blur" },
  ],
};

const showConfirmDialog = () => {
  formRef.value
    .validate()
    .then(async () => {
      let pay_img = [];
      if (fileList.value.length > 0) {
        fileList.value.map((item) => {
          pay_img.push(item.name);
        });
      } else {
        ElMessage({
          type: "error",
          message: t("请上传支付凭证"),
        });
        return false;
      }
      let msg = t("确认提交");
      if (available.value.warning) {
        msg = available.value.warning + "！" + t("确认提交");
      }
      ElMessageBox.confirm(msg, t("确认"), {
        type: "warning",
      }).then(async () => {
        form.pay_img = pay_img.join(",");
        form.pay_time = timestamp(form.pay_time.valueOf());

        // console.log(form);
        const res = await rechargeSubmitApi(form);

        ElMessage({
          type: "success",
          message: "Success",
        });
        handleClick();
        // console.log(res);
      });
    })
    .catch((error) => {
      return false;
      //      console.log(error);
    });
};
// 获取币种
const getCurrencyData = async () => {
  const res = await GetCurrencyApi();
  if (res.length) {
    currencyList.value = res.map((item) => {
      return { value: item, label: item };
    });
  }
};
// 获取充值的付款卡列表
const getPaymentCardsData = async () => {
  const res = await rechargePaymentCardsApi();
  if (res.length) {
    paymentCardsList.value = res.map((item) => {
      return { ...item };
    });
    selectList.value = res.map((item) => {
      return {
        value: `${item.send_card_number}`,
        label: `${item.send_bank} - ${item.send_card_name} - ${item.send_card_number}`,
      };
    });
    selectOptions.value = selectList.value;
  }
};
// 下拉搜索
const remoteMethod = (query) => {
  if (query) {
    loading.value = true;
    setTimeout(() => {
      loading.value = false;
      selectOptions.value = selectList.value.filter((item) => {
        return item.label.toLowerCase().includes(query.toLowerCase());
      });
    }, 200);
  } else {
    selectOptions.value = selectList.value;
  }
};
// 照片上传
const handleUploadSuccess = (res) => {
  if (res.code === 0) {
    ElMessage({
      message: t("上传成功"),
      type: "success",
    });
    fileList.value.push({
      name: res.data.name,
      url: res.data.pic_url,
    });
  } else {
    ElMessage({
      message: t("上传失败"),
      type: "error",
    });
    const newList = fileList.value.slice(0, fileList.value.length - 1);
    fileList.value = newList;
    return false;
  }
};
// 预览
const handlePictureCardPreview = (file) => {
  previewImageUrl.value = file.url;
  previewVisible.value = true;
};
// 删除照片
const handleRemove = (file) => {
  fileList.value = fileList.value.filter((item) => item.name != file.name);
};
const handleCurrencyChange = async (value) => {
  form.bank_card_id = "";
  try {
    const res = await rechargeGetBankCardsApi({ currency: value });
    //获取余额
    handleCurrency(value, form.amount);

    if (Array.isArray(res)) {
      bankCards.value = res.map((item) => {
        return {
          ...item,
        };
      });
      // 清空收款账户选择
      form.bank_card_id = "";
    } else {
      // 处理接口返回数据为空的情况
      bankCards.value = [];
      form.bank_card_id = "";
    }
  } catch (error) {
    return false;
  }
};
const handlePaymentCardChange = async (card) => {
  let new_item = paymentCardsList.value.find(
    (item) => item.send_card_number === card
  );
  if (new_item) {
    form.pay_bank_name = new_item.send_bank;
    form.pay_card_name = new_item.send_card_name;
    form.pay_bank_card_number = new_item.send_card_number;
    form.pay_bank_address = new_item.send_bank_address;
    form.pay_card_swift = new_item.send_swift_code;
    form.pay_extended = new_item.send_extended;
  } else {
    form.pay_bank_name = "";
    form.pay_card_name = "";
    form.pay_bank_card_number = "";
    form.pay_bank_address = "";
    form.pay_card_swift = "";
    form.pay_extended = "";
  }
};
getCurrencyData();
getPaymentCardsData();
</script>

<style scoped>
.el-select-dropdown__item {
  height: auto;
}

.bank-details {
  padding-right: 20px;
  border: 1px solid #ccc;
  margin: 5px 0 15px 240px;
  font-size: 14px;
  max-width: 600px;
  color: rgb(96, 98, 102);
}

.el-select-dropdown__item {
  overflow: auto;
  width: 100%;
}
</style>
